import authApi from '@/api/common/auth'
import config from '@/config'

const user = {
  state: {
    id: null,
    name: '',
    //重刷token的锁
    refreshTokenLockPromise: null
  },
  getters: {
    hasAuthInfo: state => {
      return state.id != null
    }
  },
  mutations: {
    SET_ID(state, id) {
      state.id = id
    },
    SET_NAME(state, name) {
      state.name = name;
    },
    SET_ACCESS_TOKEN(state, name) {
      state.name = name
    },
    SET_REFRESH_TOKEN(state, refreshToken) {
      state.name = name
    },
    SET_REFRESH_TOKEN_LOCK_PROMISE(state, lockPromise) {
      state.refreshTokenLockPromise = lockPromise
    },
    SET_REFRESH_TOKEN_LOCK_PROMISE_RESOLVE(state, lockPromiseResolve) {
      state.refreshTokenLockPromiseResolve = lockPromiseResolve
    }
  },
  actions: {
    login({ commit }, user) {
      return new Promise((resolve, reject) => {
        authApi.login(user).then(res => {
          if (res.data.status == "SUCCESS") {
            localStorage.setItem(config.token.accessKey, res.data.accessToken);
            localStorage.setItem(config.token.refreshKey, res.data.refreshToken);
            localStorage.setItem("isRemember", user.isRemember);
            resolve(res);
          } else {
            reject(res);
          }
        }).catch(() => {
          reject(res);
        })
      })
    },
    refreshToken({ state, commit }) {
      let lock = state.refreshTokenLockPromise;
      if (lock) {
        return lock;
      }
      return new Promise((resolve, reject) => {
        let refreshToken = localStorage.getItem(config.token.refreshKey);
        if (!refreshToken) {
          resolve(false);
          return;
        }
        let lockPromiseResolve;
        commit("SET_REFRESH_TOKEN_LOCK_PROMISE", new Promise(resolve => {
          lockPromiseResolve = resolve
        }))
        let accessToken = localStorage.getItem(config.token.accessKey);
        let isRemember = localStorage.getItem("isRemember") == "true" ? true : false;
        authApi.refreshToken({ accessToken, refreshToken, isRemember }).then(res => {
          if (res.data.status == "SUCCESS") {
            localStorage.setItem(config.token.accessKey, res.data.accessToken);
            localStorage.setItem(config.token.refreshKey, res.data.refreshToken);
            resolve(true);
            lockPromiseResolve && lockPromiseResolve(true);
          } else {
            resolve(false);
            lockPromiseResolve && lockPromiseResolve(false);
          }
          localStorage.removeItem("lock");
          commit("SET_REFRESH_TOKEN_LOCK_PROMISE", null);
        })

      });
    },
    //清空登录信息
    clearAuth() {
      localStorage.removeItem(config.token.accessKey);
      localStorage.removeItem(config.token.refreshKey);
      window.location.reload();
    },
    logout({ commit, dispatch }) {
      authApi.logout().then(() => {
        dispatch("clearAuth");
      })
    }
  }
}
export default user
